<?php
// ********************************************
// 
// Справочник модификаций моделей
//
// ********************************************

require_once( "tools.class.php" );
require_once( "tables.class.php" );
require_once( "datadefine.class.php" );

class ModifDictionary extends tables
{

    public function GetPage()
    {
        
        $data = new jqGridData();
        
        while( true )
        {
            if( $this->db == NULL ) {
                $data->userdata->errcode = 1;
                $data->userdata->errmess = "Ошибка соединения с базой данных.";
                break;
            }
            $db = $this->db;
        
// Проверяем данные
            $page    = ( isset($_REQUEST["page"]) && $_REQUEST["page"] > 0 ) ? $_REQUEST["page"] : 1;
            $limit    = ( isset($_REQUEST["rows"]) && $_REQUEST["rows"] > 0 ) ? $_REQUEST["rows"] : 1;
            $sidx    = ( isset($_REQUEST["sidx"]) && $_REQUEST["sidx"] != '' ) ? $_REQUEST["sidx"] : 'typ_id';
            $sord    = ( isset($_REQUEST["sord"]) && strtolower($_REQUEST["sord"]) == 'desc' ) ? 'DESC' : 'ASC';
            $search    = ( isset($_REQUEST["_search"]) && strtolower($_REQUEST["_search"]) == 'true') ? true : false;
    
// Фильтр
            $whc = array();
 
            $model_id = isset($_REQUEST["typ_model_id"]) ? $_REQUEST["typ_model_id"] : '';
            if( $model_id === '' ) {
                break;              // Модель пока не указана
            }
            if( !is_numeric($model_id) ) {
                $data->userdata->errcode = 1;
                $data->userdata->errmess = "Нарушение формата данных.";
                break;
            }
            else {
                $whc[] = "typ_model_id=" . $db->quote($model_id);
            }
            
            $whereclaus = (count($whc) != 0 ) ? " WHERE " . implode(" AND ", $whc) : "";
            unset($whc);
    
// Получаем количество записей с учетом фильтра
            $sqlreq = "SELECT COUNT(*) as count FROM modifics " . $whereclaus;
            $recset = $db->query( $sqlreq );
            $row = $recset->fetch(PDO::FETCH_ASSOC);
            $count = $row['count'];
            $recset->closeCursor();
    
    // Пустая таблица
            if ($count == 0) break;
    
    // Рассчитаем сколько всего страниц займут данные в БД
            if( $count > 0 && $limit > 0) {
                $total_pages = ceil($count/$limit);
            } else {
                $total_pages = 0;
            }                  
     
    // Если по каким-то причинам клиент запросил
            if ($page > $total_pages) $page=$total_pages;                  
     
    // Рассчитываем стартовое значение для LIMIT запроса
            $start = $limit*$page - $limit;                  
     
    // Зашита от отрицательного значения
            if($start < 0) $start = 0;                  
     
    // Формируем запрос
            $sqlreq = "SELECT ".
                "typ_id, typ_model_id, lng_text.text_text AS full_name, pcon_start, pcon_end, kw_from, hp_from, ccm, ".
                "body_text.text_text AS body_des, axis_text.text_text AS axis_des, max_weight, ".
                "engine_text.text_text AS engine_des, fuel_text.text_text AS fuel_des, ".
                "FROM modifics INNER JOIN models ON typ_model_id = model_id ".
                "LEFT OUTER JOIN cdesign AS lng_des ON full_cdes_id = lng_des.cdes_id ".
                "LEFT OUTER JOIN descriptions AS lng_text ON lng_des.text_id = lng_text.text_id ".
                "LEFT OUTER JOIN design AS body_des ON body_des_id = body_des.des_id ".
                "LEFT OUTER JOIN descriptions AS body_text ON body_des.text_id = body_text.text_id ".
                "LEFT OUTER JOIN design AS axis_des ON axis_des_id = axis_des.des_id ".
                "LEFT OUTER JOIN descriptions AS axis_text ON axis_des.text_id = axis_text.text_id ".
                "LEFT OUTER JOIN design AS engine_des ON engine_des_id = engine_des.des_id ".
                "LEFT OUTER JOIN descriptions AS engine_text ON engine_des.text_id = engine_text.text_id ".
                "LEFT OUTER JOIN design AS fuel_des ON fuel_des_id = fuel_des.des_id ".
                "LEFT OUTER JOIN descriptions AS fuel_text ON fuel_des.text_id = fuel_text.text_id ".
                $whereclaus." ORDER BY ".$sidx." ".$sord." LIMIT ".$start.", ".$limit;
                    
            $recset = $db->query($sqlreq);                  
     
    // Формирование объекта для возврата
            $data->page      = $page;
            $data->total     = $total_pages;
            $data->records   = $count;
            
    // Строки данных для таблицы
            $i = 0;
            while($row = $recset->fetch(PDO::FETCH_ASSOC)) {
                $data->rows[$i]['id'] = $row['typ_id'];
                $data->rows[$i]['cell'] = array(
                        $row['typ_id'], $row['typ_model_id'], $row['full_name'], $row['pcon_start'], $row['pcon_end'],
                        $row['kw_from'], $row['hp_from'], $row['ccm'], $row['body_des'], $row['axis_des'],
                        $row['max_weight'], $row['engine_des'], $row['fuel_des']
                );
                $i++;
            }
            break;
        }    
// Отдаем результат
        header("Content-type: text/script;charset=utf-8");
        echo json_encode($data);
        return;
    }

//
// Добавление новой модели
//
    public function Insert()
    {
    }

//
// Изменение в записи модели
//
    public function Update()
    {
    }

//
// Удалить список моделей
//
    public function Delete()
    {
    }

//
// Найти список по подстроке в имени
//    
    public function Find()
    {
    }

    
    public function GetList()
    {
        $model_id = isset($_REQUEST['node_id']) ? $_REQUEST['node_id'] : '';
        $errmess = "";
        $node = array();
        
        while( true ) {
            if( !is_numeric($model_id)) {
                $errmess = "Нарушение формата данных";
                break;
            }

            if( $this->db == NULL ) {
                $errmess = "Ошибка соединения с базой данных.";
                break;
            }
            $db = $this->db;

// Получаем количество записей с учетом фильтра
            $recset = $db->query( "SELECT COUNT(*) as count FROM modifics WHERE typ_model_id=".$db->quote($model_id) );
            $row = $recset->fetch(PDO::FETCH_ASSOC);
            $count = $row['count'];
            $recset->closeCursor();

// Пустая таблица
            if ($count == 0) break; 

// Формируем запрос
            $sqlreq = "SELECT typ_id, typ_model_id, typ_vendor_id, lng_text.text_text AS full_name ".
                "FROM modifics INNER JOIN models ON typ_model_id = model_id ".
                "LEFT OUTER JOIN cdesign AS lng_des ON full_cdes_id = lng_des.cdes_id ".
                "LEFT OUTER JOIN descriptions AS lng_text ON lng_des.text_id = lng_text.text_id ".
                "WHERE typ_model_id=".$db->quote($model_id)." ORDER BY full_name";

            $recset = $db->query($sqlreq);                  
 
// Строки данных для таблицы
            while($row = $recset->fetch(PDO::FETCH_ASSOC)) {
                $unit = new DynaTreeNode();
                $unit->key = $row['typ_vend_id'].".".$row['typ_model_id'].".".$row['typ_id'];
                $unit->title = $row['full_name'];
                $unit->isFolder = false;
                $unit->isLazy = false;
                $node[] = $unit;
            }
            $recset->closeCursor();

            break;
        }
        
        header("Content-type: text/script; charset=utf-8");
        echo json_encode($node);

        return;
    }
    
} //End of class ModifDictionary
?>
